from flask import current_app


class UniqueMixin(object):
    @classmethod
    def get_unique(cls, **kwargs):
        session = current_app.extensions['sqlalchemy'].db.session
        session._unique_cache = cache = getattr(session, '_unique_cache', {})
        key = (cls, tuple(kwargs.items()))
        o = cache.get(key)
        if o is None:
            o = session.query(cls).filter_by(**kwargs).first()
            print('o',o)
            if o is None:
                o = cls(**kwargs)
                session.add(o)
            cache[key] = o
        return o
